<template>
  <div class="asset-ledger-container">
    <h2>资产台账</h2>
    
    <div class="filter-bar">
      <el-input v-model="searchKeyword" placeholder="搜索资产名称/编号" style="width: 300px;" />
      <el-select v-model="statusFilter" placeholder="选择状态">
        <el-option label="全部状态" value="" />
        <el-option label="在用" value="在用" />
        <el-option label="闲置" value="闲置" />
        <el-option label="维修" value="维修" />
        <el-option label="报废" value="报废" />
        <el-option label="借用" value="借用" />
      </el-select>
      <el-select v-model="deptFilter" placeholder="选择部门">
        <el-option label="全部部门" value="" />
        <el-option label="技术部" value="技术部" />
        <el-option label="市场部" value="市场部" />
        <el-option label="行政部" value="行政部" />
        <el-option label="财务部" value="财务部" />
        <el-option label="人力资源部" value="人力资源部" />
        <el-option label="运营部" value="运营部" />
      </el-select>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetFilters">重置</el-button>
      <el-button type="success" @click="exportExcel">导出Excel</el-button>
    </div>
    
    <el-card>
      <el-table 
        :data="assetList" 
        style="width: 100%"
        border
        stripe
        :default-sort="{prop: 'purchaseDate', order: 'descending'}"
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="assetCode" label="资产编号" width="180" />
        <el-table-column prop="assetName" label="资产名称" min-width="180" />
        <el-table-column prop="assetType" label="资产类型" width="120" />
        <el-table-column prop="status" label="状态" width="100" />
        <el-table-column prop="department" label="所属部门" width="120" />
        <el-table-column prop="userName" label="使用人" width="100" />
        <el-table-column prop="purchaseDate" label="采购日期" width="150" />
        <el-table-column prop="value" label="价值" width="120" :formatter="formatMoney" />
        <el-table-column prop="supplier" label="供应商" min-width="150" />
        <el-table-column prop="location" label="存放位置" min-width="150" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewDetail(scope.row)">查看</el-button>
            <el-button size="small" type="primary" @click="editAsset(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 详情对话框 -->
    <el-dialog v-model="detailVisible" title="资产详情" width="600px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="资产编号">{{ selectedAsset?.assetCode }}</el-descriptions-item>
        <el-descriptions-item label="资产名称">{{ selectedAsset?.assetName }}</el-descriptions-item>
        <el-descriptions-item label="资产类型">{{ selectedAsset?.assetType }}</el-descriptions-item>
        <el-descriptions-item label="当前状态">{{ selectedAsset?.status }}</el-descriptions-item>
        <el-descriptions-item label="所属部门">{{ selectedAsset?.department }}</el-descriptions-item>
        <el-descriptions-item label="使用人">{{ selectedAsset?.userName }}</el-descriptions-item>
        <el-descriptions-item label="采购日期">{{ selectedAsset?.purchaseDate }}</el-descriptions-item>
        <el-descriptions-item label="资产价值">{{ selectedAsset?.value ? formatMoney(null, null, selectedAsset.value) : '-' }}</el-descriptions-item>
        <el-descriptions-item label="预计使用年限">{{ selectedAsset?.expectedLife }}年</el-descriptions-item>
        <el-descriptions-item label="折旧方法">{{ selectedAsset?.depreciationMethod }}</el-descriptions-item>
        <el-descriptions-item label="供应商">{{ selectedAsset?.supplier }}</el-descriptions-item>
        <el-descriptions-item label="存放位置">{{ selectedAsset?.location }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ selectedAsset?.remark || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>




<script setup>
import { ref, onMounted } from 'vue'
import { selectInfoByNameAndStatusAndDeptNameAPI } from '@/api/asset.js'
import { ElMessage } from 'element-plus'

//定义报表筛选数据
const filterForm = ref({
  assetName:'',
  categroy:'',// 默认选中“全部类型”
  deptName: ''    // 默认选中“全部部门”
})
const assetList = ref([]) // 资产列表数据
const currentPage = ref(1) // 当前页码
const pageSize = ref(20) // 每页条数
const total = ref(1528) // 总记录数（后续可从接口返回动态更新）
const detailVisible = ref(false) // 详情弹窗显示状态
const selectedAsset = ref(null) // 选中的资产详情


// 金额格式化（保留原逻辑）
const formatMoney = (cellValue) => {
  return '¥' + cellValue.toLocaleString('zh-CN')
}

//数据加载
const loadData = async () => {
  try {
    // 调用后端接口，传入筛选条件、分页参数
    const res = await selectInfoByNameAndStatusAndDeptNameAPI({
      name: filterForm.assetName.value, // 资产名称
      status: filterForm.categroy.value, // 资产状态
      deptName: filterForm.deptName.value, // 部门名称
      pageNum: currentPage.value, // 当前页码
      pageSize: pageSize.value // 每页条数
    })

    if (res.code === 200) {
      assetList.value = res.data.list || [] // 资产列表数据
      total.value = res.data.total || 0 // 动态更新总记录数（替代硬编码）
    } else {
      assetList.value = []
      total.value = 0
      ElMessage.warning('暂无资产数据')
    }
  } catch (error) {
    console.error('加载资产数据失败：', error)
    assetList.value = []
    total.value = 0
    ElMessage.error('数据加载失败，请重试')
  }
}

// 搜索（筛选条件提交）
const handleSearch = () => {
  loadData()
}

// 重置筛选条件
const resetFilters = () => {
  searchKeyword.value = ''
  statusFilter.value = ''
  deptFilter.value = ''
  loadData()
}

// 每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size
  loadData()
}

// 当前页码变化
const handleCurrentChange = (current) => {
  currentPage.value = current
  loadData()
}

// 查看资产详情
const viewDetail = (asset) => {
  selectedAsset.value = { ...asset } // 深拷贝，避免修改原数据
  detailVisible.value = true
}

// 编辑资产
const editAsset = (asset) => {
  console.log('编辑资产:', asset)
  ElMessage.info('编辑功能待实现')
}

// ==================== 生命周期 ====================
// 组件挂载时加载初始数据
onMounted(() => {
  loadData()
})

// 暴露方法给模板（金额格式化需手动暴露，其他ref变量自动解包）
defineExpose({
  formatMoney
})
</script>

<style scoped>
.asset-ledger-container {
  padding: 20px;
}

.filter-bar {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  flex-wrap: wrap;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>